import { insetAddress, delAddress, findAddress } from '/api/address';
import city from '/utils/newCity';
Page({
  data: {
    systemInfo: null, //系统信息
    id: '0',
    receiver_name: '',
    receiver_phone: '',
    area: '',
    address: '',
    city_index: [],
    cityList: city,
    provinces: '', //省
    city: '', //市
    district: '' // 区
  },
  onLoad(opts) {
    const { 
      id, 
      receiver_name,
      receiver_phone,
      address,
      provinces,
      city,
      district,
      platform
    } = opts;

    if(id) { // 编辑地址进来
      this.setData({
        id,
      });
      this.getAddressById()
    }

    // 获取支付宝地址进来
    if(receiver_phone) {
      this.setData({
        receiver_name,
        receiver_phone,
        provinces,
        city,
        district,
        address,
        area: `${provinces}${city}${district}`
      })
      this.getAddressSelectOptions()
    }
    let app = getApp();
    app.setShareChannel(platform)
  },

  getAddressSelectOptions() {
    const {
      provinces,
      city,
      district,
    } = this.data

    let addressRes = []
    const proviceRes = this.data.cityList.find(item => {
     return item.label === provinces
    })

    // 若数据，某些城市和支付宝对不上直接为空
    if(proviceRes) {
      addressRes.push(proviceRes.value) // 有省份直接添加
      const cityRes = proviceRes.children.find(item => 
         item.label === city
      )

      if(cityRes) {  // 有城市直接添加
        addressRes.push(cityRes.value)
        let districtRes = cityRes.children.find(item => 
             item.label === district
        )
        // 有区域直接添加
        districtRes ? addressRes.push(districtRes.value) : addressRes = []
      } else {
        // 城市不对直接为空
        addressRes = []
      }
    } else {
      addressRes = [] // 省份对不上
    }

    this.setData({
      city_index: addressRes
    })
  },
  

  async getAddressById() {
    const res = await findAddress({ id: this.data.id });
    
    let { 
      receiver_name, 
      receiver_phone, 
      address, 
      city_index, 
      area,
      provinces, 
      city, 
      district
    } = res.data;

    let addressRes = []
    const proviceRes = this.data.cityList.find(item => {
     return item.label === provinces
    })


    // 若数据，某些城市和支付宝对不上直接为空
    if(proviceRes) {
      addressRes.push(proviceRes.value) // 有省份直接添加
      const cityRes = proviceRes.children.find(item => 
         item.label === city
      )

      if(cityRes) {  // 有城市直接添加
        addressRes.push(cityRes.value)
        let districtRes = cityRes.children.find(item => 
             item.label === district
        )
        // 有区域直接添加
        districtRes ? addressRes.push(districtRes.value) : addressRes = []
      } else {
        // 城市不对直接为空
        addressRes = []
      }
    } else {
      addressRes = [] // 旧的数据省份对不上
    }


    // 只要省市区任一为空，下拉和详细地址为空
    if(!provinces || !city || !district) {
      city_index = []
      address = ''
    }


    if(!city_index) { // 有可能返回空字符串
      city_index = []
    }


    if(city_index.length && city_index[0].length !== 7) { // 是数组且有数据，判断是老地址还是新地址
      city_index = addressRes// 有旧的数据直接覆盖成新的
    }

    if(!city_index.length && addressRes.length) { // 没有地址，使用下拉选项的地址
      city_index = addressRes
    }

    this.setData({
      receiver_name,
      receiver_phone,
      address,
      area,
      provinces, 
      city, 
      district,
      city_index
    });
  },

 

  handleValuesChange(value, values) {
    console.log(value, values);
  },
  submit(e) {

    if (!this.data.receiver_name) {
      my.showToast({
        type: 'none',
        content: '请输入收货人姓名！',
        duration: 1000,
      });
      return;
    }
    if (!this.data.receiver_phone) {
      my.showToast({
        type: 'none',
        content: '请输入收货人手机！',
        duration: 1000,
      });
      return;
    }
    let regPhone = /^1\d{10}$/;
    if (!regPhone.test(this.data.receiver_phone)) {
      my.showToast({
        type: 'none',
        content: '收货人手机格式不正确！',
        duration: 1000,
      });
      return;
    }


    if (this.data.city_index.length === 0) {
      my.showToast({
        type: 'none',
        content: '请选择地区！',
        duration: 1000,
      });
      return;
    }

    if (!this.data.address) {
      my.showToast({
        type: 'none',
        content: '请输入详细地址！',
        duration: 1000,
      });
      return;
    }
    const zm_user_id = my.getStorageSync({ key: 'zm_user_id' }).data;
    const {
      provinces,
      city,
      district
    } = this.data
    insetAddress({
      id: this.data.id ? this.data.id : '',
      zm_user_id,
      receiver_name: this.data.receiver_name,
      receiver_phone: this.data.receiver_phone,
      address: this.data.address,
      city_index: this.data.city_index,
      area: this.data.area,
      provinces,
      city,
      district
    }).then((res) => {
      const {
        status,
        msg
      } = res
      if(status !== '1001') {
        my.showToast({
          type: 'none',
          content: msg
        })
        return
      }
      my.navigateBack();
    });
  },
  handleNameInput(e) {
    this.setData({
      receiver_name: e.detail.value,
    });
  },
  handlePhoneInput(e) {
    this.setData({
      receiver_phone: e.detail.value,
    });
  },
  handleMailInput(e) {
    this.setData({
      email: e.detail.value,
    });
  },
  handleAddressInput(e) {
    this.setData({
      address: e.detail.value,
    });
  },
  del() {
    my.confirm({
      title: '温馨提示',
      content: '您是否想删除当前收获地址',
      confirmButtonText: '删除',
      cancelButtonText: '暂不',
      success: (res) => {
        if(res.confirm) {
          delAddress({
            id: parseInt(this.data.id),
          })
            .then(() => {
              my.navigateBack();
            })
            .catch(() => {
              my.showToast({
                type: 'none',
                content: '删除失败',
                duration: 1000,
              });
            });
        } else {
          my.showToast({
            type: 'none',
            content: '已取消删除',
            duration: 1000,
          });
        }
      },
    });
  },
  handleOk(value, selectedOption, e) {
    
    // if(value.length !== 3) {
    //   my.showToast({
    //     type: 'none',
    //     content: '暂不支持该省份地区'
    //   })
    // }

    // this.setData({
    //   area:
    //     selectedOption[0].label +
    //     selectedOption[1].label +
    //     selectedOption[2].label || '',
    //   city_index: value,
    //   provinces: selectedOption[0].label,
    //   city: selectedOption[1].label,
    //   district: selectedOption[2].label
    // });

    // if(value.length !== 3) {
    //   my.showToast({
    //     type: 'none',
    //     content: '暂不支持该省份地区'
    //   })
    // }


    const [prov, citys, districts] = selectedOption
    const city = citys ? citys.label: '';
    const district = districts ? districts.label: '';

    this.setData({
      area: `${prov.label}${city}${district}`,
      city_index: value,
      provinces: prov.label,
      city,
      district
    });
  },
});
